import React, { useState, useEffect } from 'react'
import { View } from '@tarojs/components'

import './index.scss'
import { Icon } from '../Icon'

export interface IRateProps {
    value: number
    readonly?: boolean
    disabeld?: boolean
    size?: number
    icon?: string
    voidIcon?: string
    color?: string
    voidColor?: string
    disabledColor?: string
    count?: number
    gutter?: string
    onClick?: Function
}

export const Rate: React.FC<IRateProps> = ({
    count = 5,
    gutter = '5px',
    icon = 'favorite-filling',
    voidIcon = 'favorite',
    color = '#F9AC19',
    size = 28,
    voidColor = '#EFEFF4',
    disabledColor = '#e8e8e8',
    onClick,
    ...rest
}) => {

    const [innerValue, setInnerValue] = useState<number>(rest.value)
    const [innerArr, setInnerArr] = useState<Array<any>>(Array.from({ length: count }))

    useEffect(() => {
        if (rest.value !== null && rest.value !== undefined) {
            setInnerValue(rest.value)
        }
    }, [rest.value])

    useEffect(() => {
        setInnerArr(Array.from({ length: count }))
    }, [count])


    return (
        <View className="xxm-rate-ls">
            {
                innerArr.map((_, idx) => {
                    const sl = idx + 1 <= innerValue
                    return (
                        <View
                            className="xxm-rate-ls__item"
                            key={idx}
                            style={{ paddingRight: idx != count - 1 ? gutter : 0 }}
                            onClick={
                                () => {
                                    setInnerValue(idx + 1);
                                    onClick && onClick(idx + 1)
                                }
                            }
                        >

                            <Icon
                                name={sl ? icon : voidIcon}
                                size={size}
                                color={rest.disabeld ? disabledColor : sl ? color : voidColor}
                            />
                        </View>
                    )
                })
            }
        </View>
    )
}